package bma.common.thrift.common;

import org.apache.thrift.TException;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.THttpClient;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;

import bma.common.langutil.core.Preconditions;
import bma.common.langutil.io.HostPort;
import bma.common.thrift.ThriftClient;
import bma.common.thrift.ThriftClientConfig;
import bma.common.thrift.ThriftClientFactory;

public class ThriftClientFactoryCommon implements ThriftClientFactory {

	final org.slf4j.Logger log = org.slf4j.LoggerFactory
			.getLogger(ThriftClientFactoryCommon.class);

	protected TTransport createTransport(ThriftClientConfig cfg)
			throws TException {
		TTransport transport = null;
		if (cfg.isHttp()) {
			String url = cfg.getUrl();
			Preconditions.checkNotNull(url);
			if (log.isDebugEnabled()) {
				log.debug("create http client - {}", url);
			}
			transport = new THttpClient(url);
		} else {
			HostPort host = cfg.getHost();
			Preconditions.checkNotNull(cfg.getHost());
			if (log.isDebugEnabled()) {
				log.debug("create socket client - {}", cfg.getHost());
			}
			transport = new TSocket(host.getHost(), host.getPort(9090));
		}
		transport.open();
		if (cfg.getFrameMaxLength() > 0) {
			transport = new TFramedTransport(transport, cfg.getFrameMaxLength());
		}
		return transport;
	}

	@Override
	public ThriftClient createThriftClient(ThriftClientConfig cfg)
			throws TException {
		TTransport transport = createTransport(cfg);
		TProtocol tprotocol = cfg.createProtocol(transport, null);

		return new ThriftClientCommon(transport, tprotocol);
	}

}
